#include "tcpserver.h"
#include "inetaddress.h"
#include "tinyrpc/base/logger/logger.h"
namespace TinyRPC{

TcpServer::TcpServer(EventLoop* baseLoopPtr,int threadNum)
: m_baseLoopPtr(baseLoopPtr)
, m_threadNum(threadNum)
, m_eventLoopPool(threadNum)
, m_nextLoopIndex(0){

}


TcpServer::~TcpServer(){
    m_eventLoopPool.quit();
}
void TcpServer::start(){
    m_eventLoopPool.start();
    //m_baseLoop.loop();
}


void TcpServer::co_echo(SocketChannelPtr socketChannel){
    socketChannel->receiveFromRemote();
    std::string buffer = socketChannel->read();
    socketChannel->write(buffer);

}


void TcpServer::co_accept(INetAddress address){
    
    ServerSocketChannel server = ServerSocketChannel::CreateAndBind(address);
    server.listen();
    while (1)
    {
        SocketChannelPtr socketChannel = server.accept();
        getNextLoop()->runInLoop(Task(std::bind(&TcpServer::co_echo, this, socketChannel), true));
        socketChannel.reset();
    }
    
}

}
